package game.source.util;

/*Timer:
 * Executa uma função depois de um determindado tempo
 */
public class Timer extends Thread{
	private boolean	end;
	private boolean	pause;
	private int		millisec;
	private long	delta;
	TimerListener	listener;

	public Timer(TimerListener listener, int millisec){
		this.end = false;
		this.pause = false;
		this.millisec = millisec;
		this.listener = listener;
	}
	@Override
	public void run() {
		while(!this.end){
			synchronized (this) {
				while(this.pause){
					try {
						this.wait();
					} catch(InterruptedException e){
						e.printStackTrace();
					}
				}	
			}
			try{
				long t1 = System.currentTimeMillis();
				this.listener.update();
				this.delta = System.currentTimeMillis() - t1;
				if(this.millisec - this.delta > 0)
					Thread.sleep(this.millisec - this.delta);
			}catch (Exception e){
				System.err.println("Erro no Timer: ");
				e.printStackTrace();
				System.exit(1);
			}
		}
	}
	public int getMilisec(){
		return this.millisec;
	}
	public void setMilisec(int millisec){
		this.millisec = millisec;
	}
	public boolean isPaused(){
		return this.pause;
	}
	public void pause(){
		this.pause = true;
	}
	public synchronized void play(){
		this.pause = false;
		this.notify();
	}
	public void end(){
		this.end = true;
	}
	public long getDelta(){
		if(this.delta > this.millisec)
			return this.delta;
		else
			return this.millisec;
	}
}
